<?php

//调试输出。
if (defined('DEBUG')){
class Debug{
	static $id = null;
	static function getKey(){
		if(is_null(self::$id)){
			$id = intval(session('debugid')); session('debugid', ($id + 1) % DEBUG_PAGES );
			self::$id = $id;
			session("debugmsg{$id}", null); 
			$line = $_SERVER['REQUEST_URI'] . '  ' . date(DATE_W3C);
			sessiona("debugmsg{$id}", $line); 
			$line = print_r($_REQUEST, true);
			sessiona("debugmsg{$id}", $line); 
		}
		return self::$id;
	}
	static function addLine($line){ 
		if (! session('indebug')) return; 
		if (is_null($line)) return;
		$id = self::getKey();
		sessiona("debugmsg{$id}", $line); 
	}
	static function Log($obj){
		$backtrace = debug_backtrace();
		$l = $backtrace[0]['line'];
		$f = $backtrace[0]['file'];
		$text =("$f:$l\n" . print_r($obj, true));
		$text = str_replace(array("\r\n", "\r", "\n\n"), "\n", $text);
		$text = str_replace(array("\r\n", "\r", "\n\n"), "\n", $text);
		$txt = explode("\n", $text);
		foreach($txt as $t){
			self::addLine( $t );
		}
	}
	static function LogSql($sql){
		$backtrace = debug_backtrace();
		$l = $backtrace[1]['line'];
		$f = $backtrace[1]['file'];
		$t = addslashes("$f:$l");
		self::addLine( $t );
		$t = addslashes($sql);
		self::addLine( $t );
	}
	static function SqlError($sql){
		$t = addslashes($sql);
		self::addLine( $t );
	}
	static function Exception($e) {
		self::addLine( '!!!Exception!!!' );
		self::addLine( $e->getMessage());
		self::Trace();
		self::addLine( '--- end ---' );
	}
	static function Error($errno, $errstr, $errfile, $errline) {
		self::addLine( '!!!Error!!!' );
		$errstr = addslashes($errstr);
		$error = "[$errno] $errstr ".$errfile." 第 $errline 行.";
		self::addLine( $error );
		self::Trace();
		self::addLine( '--- end ---' );
	}
	static function Trace(){
		self::addLine( 'Call Stack:' );
		$dtraces = debug_backtrace();
		foreach($dtraces as $t){
			$txt = $t['file'] . ":" . $t['line'] ;
			self::addLine( $txt );
		}
	}

}
} else{
class Debug{
	static function Log($obj){}
	static function LogSql($sql){}	
	static function SqlError($sql){}		
	static function Error($errno, $errstr, $errfile, $errline) {}
	static function Exception($e) {}
}
}
